﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FindArbitrageConsole.Data.Model;
using Microsoft.Practices.Unity;

namespace FindArbitrageConsole.Data.Repository
{
    public class MaxKefRepository
    {
        [Dependency]
        public IDataService DataService { get; set; }

        private DateTime LastUpdateTime { get; set; }

        private List<KefData> _maxKefs;
        public List<KefData> MaxKefs
        {
            get
            {
                DoProcess();
                return _maxKefs;
            }
        }

        public List<KefData> GetLocalMaxKefs()
        {
            return _maxKefs;
        }

        private void DoProcess()
        {
            if (_maxKefs == null || !_maxKefs.Any())
                ReadAllRecords();
            else
                UpdateRecords();
        }
        private void ReadAllRecords()
        {
            _maxKefs = DataService.GetAllMaxKefs().ToList();
            if (_maxKefs.Count == 0)
                return;
            LastUpdateTime = _maxKefs.Max(k => k.UpdateTime);
        }
        private void UpdateRecords()
        {
            var appendedKefs = DataService.GetAllMaxKefsAfterUpdateTime(LastUpdateTime);

            if (!appendedKefs.Any())
                return;

            var exists = appendedKefs.Where(kef => _maxKefs.FirstOrDefault(k => k.Id == kef.Id) != null).ToList();
            var news = appendedKefs.Except(exists);

            exists.ForEach(kef =>
            {
                var kefObj = _maxKefs.First(k => k.Id == kef.Id);
                kefObj.KefValue = kef.KefValue;
                kefObj.UpdateTime = kef.UpdateTime;
            });
            _maxKefs.AddRange(news);


            LastUpdateTime = appendedKefs.Max(k => k.UpdateTime);
        }
    }
}
